package com.cw.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cw.annotation.OperationLogAnno;
import com.cw.common.api.Response;
import com.cw.common.constant.Constants;
import com.cw.common.method.CommonMethod;
import com.cw.common.method.SendCardMsg;
import com.cw.dto.InpatientRegistrationCondition;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.request.AllSickBedsRequest;
import com.cw.response.EmptyBedsResponse;
import com.cw.service.IOccupationBedService;
import com.cw.service.IPatientBedMiddlePrebundledService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.util.HttpUtil;
import com.cw.util.MQMsg;
import com.cw.util.UUIDUtil;
import com.cw.vo.LeaveAdviceVO;
import com.cw.vo.spdVO;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import net.sf.cglib.core.Local;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.cw.service.impl.HisCwglBedServiceImpl.seniorRoomNum;

/**
 * <p>
 * 预绑定患者信息表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-02-19
 */
@Service
public class PatientBedMiddlePrebundledServiceImpl extends ServiceImpl<PatientBedMiddlePrebundledMapper,
        PatientBedMiddlePrebundled> implements IPatientBedMiddlePrebundledService {

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;

    @Autowired
    private ThisIiPrepayinServiceImpl thisIiPrepayinService;

    @Autowired
    private HisCwglBedMapper hisCwglBedMapper;

    @Resource
    private ThisIiInmaininfoMapper thisIiInmaininfoMapper;

    @Autowired
    private ListeningLogServiceImpl listeningLogService;

    @Autowired
    private PatientBedMiddleMapper patientBedMiddleMapper;

    @Autowired
    private PatientBedMiddleServiceImpl patientBedMiddleService;

    @Autowired
    private WeChatLogMapper weChatLogMapper;

    @Autowired
    private TelMessageMapper telMessageMapper;

    @Autowired
    private ApplicationBedMapper applicationBedMapper;

    private static ReentrantLock lock = new ReentrantLock();

    private MQMsg mqMsg = new MQMsg();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addPrebundled(String bedId, String patientId, String name) {
        lock.lock();
        try {
            //判断是否被预绑定
            List<PatientBedMiddlePrebundled> patientBedMiddlePrebundleds =
                    baseMapper.selectList(new LambdaQueryWrapper<>(
                            new PatientBedMiddlePrebundled()).eq(PatientBedMiddlePrebundled::getBedNo, bedId)
                            .eq(PatientBedMiddlePrebundled::getState, "1"));
            if (CollectionUtils.isNotEmpty(patientBedMiddlePrebundleds)) {
                return new Response(500, "床位预绑定失败,该床已被预绑定");
            }
            //判断预绑定患者状态 0取消预约2转入院3出院9作废
            //获取患者信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            if ("0".equals(thisIiPrepayin.getPreState())) {
                return new Response(500, "床位预约失败，该患者电子住院证已取消");
            } else if ("1".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已预约床位");
            } else if ("2".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已入院");
            } else if ("3".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已出院");
            } else if ("9".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者电子住院证已作废");
            }
            //根据床位编码获取床位信息
            HisCwglBed hisCwglBed =
                    hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo,
                            bedId)).get(0);
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);
            String realName = HttpUtil.getRequestHeaderInfo("realname");
            //根据病人PreId获取病人信息
            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(patientId);
            PatientBedMiddlePrebundled patientBed = new PatientBedMiddlePrebundled();
            patientBed.setId(UUIDUtil.uuid());
            patientBed.setBedNo(bedId);
            patientBed.setName(name);
            patientBed.setIdenno(thisIiPrepayin.getIdenno());
            patientBed.setPreid(thisIiPrepayin.getPreid());
            patientBed.setYard(hisCwglBed.getYard());
            patientBed.setNurseCellCode(hisCwglBed.getNurseCellCode());
            patientBed.setNurseCellName(hisCwglBed.getNurseCellName());
            patientBed.setNurseCellCodeBefore(thisIiPrepayin.getNurseCellCode());
            patientBed.setDeptCode(hisCwglBed.getDeptCode());
            patientBed.setDeptName(hisCwglBed.getDeptName());
            //1：预绑定  2：真实绑定  3：已取消预绑定
            patientBed.setState("1");
            patientBed.setOperNo(userId);
            patientBed.setOpenName(userName);
            patientBed.setOperTime(LocalDateTime.now());
            //如果电子住院证中有住院号,将住院号回写至预约表(先去住院处登记的情况)
            patientBed.setInpatientNo(patientInfo.getInpatientNo());
            //信息插入预绑定表
            baseMapper.insert(patientBed);
        } catch (Exception e) {
            return new Response(500, "预绑定失败");
        } finally {
            lock.unlock();
        }
        return new Response(200, "预绑定成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updatePrebundled(String bedId, String patientId) {
        LambdaUpdateWrapper<PatientBedMiddlePrebundled> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(PatientBedMiddlePrebundled::getPreid, patientId)
                .eq(PatientBedMiddlePrebundled::getBedNo, bedId)
                .eq(PatientBedMiddlePrebundled::getState, "1")
                .set(PatientBedMiddlePrebundled::getState, "3");
        boolean update = update(lambdaUpdateWrapper);
        if (!update) {
            return new Response(500, "预绑定取消失败");
        }
        return new Response(200, "预绑定取消成功");
    }

    @Override
    public List<EmptyBedsResponse> listPreBoundWard(AllSickBedsRequest param) {
        List<LeaveAdviceVO> leaveAdviceVOList = new ArrayList<>();
        String leaveHospitalToday = null;
        String leaveHospitalTomorrow = null;
        List<EmptyBedsResponse> resultBeds = new ArrayList<>();
        //根据院区获取所有集管床位
        List<HisCwglBed> boundGyBeds = baseMapper.getBoundGyBeds(param);
        List<PatientBedMiddlePrebundled> patientBedMiddlePrebundleds = baseMapper.patientList();
        if (boundGyBeds == null || boundGyBeds.isEmpty()) {
            return resultBeds;
        }
        List<String> inpatientNoList = boundGyBeds.stream()
                .map(HisCwglBed::getInpatientNo)
                .collect(Collectors.toList());
        //移除null元素
        inpatientNoList.removeAll(Collections.singleton(null));
        if (!inpatientNoList.isEmpty()) {
            leaveAdviceVOList = baseMapper.leaveAdviceList(inpatientNoList);
            for (LeaveAdviceVO item : leaveAdviceVOList) {
                if ("临时出院".equals(item.getChangeType()) || "自动出院".equals(item.getChangeType())) {
                    item.setChangeType("今日出院");
                }
            }
        }
        SetSexRoom(boundGyBeds);
        //根据病区分组(页面上显示病区分组)
        Map<String, List<HisCwglBed>> groupList = boundGyBeds.stream()
                .collect(Collectors.groupingBy(t -> t.getNurseCellCode() + "-" + t.getDeptCode()));
        Iterator<String> it = groupList.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            //这里可能存在一个病区多个科室的情况,所以这里要根据科室分一下组
            List<HisCwglBed> operLst = boundGyBeds.stream()
                    .filter(t -> (t.getNurseCellCode() + "-" + t.getDeptCode()).equals(key))
                    .collect(Collectors.toList());
            //院区科室内一共集管床位总数
            int size = operLst.size();
            List<String> bedNoList = operLst.stream().map(HisCwglBed::getBedNo).collect(Collectors.toList());
            //预绑定集管床位总数
            int filterSize = 0;
            if (!patientBedMiddlePrebundleds.isEmpty()) {
                filterSize = patientBedMiddlePrebundleds.stream()
                        .filter(t -> bedNoList.contains(t.getBedNo()) && "1".equals(t.getState()))
                        .collect(Collectors.toList())
                        .size();
            }
            HisCwglBed info = operLst.get(0);
            List<String> inpatienGroup = operLst.stream().map(HisCwglBed::getInpatientNo).collect(Collectors.toList());
            List<LeaveAdviceVO> leaveAdviceVOS = leaveAdviceVOList.stream()
                    .filter(t -> inpatienGroup.contains(t.getInpatientNo()))
                    .collect(Collectors.toList());
            //今日出院跟明日出院计数
            leaveHospitalToday = String.valueOf(leaveAdviceVOS.stream()
                    .filter(t -> "今日出院".equals(t.getChangeType()))
                    .collect(Collectors.toList())
                    .size());
            leaveHospitalTomorrow = String.valueOf(leaveAdviceVOS.stream()
                    .filter(t -> "明日出院".equals(t.getChangeType()))
                    .collect(Collectors.toList())
                    .size());
            EmptyBedsResponse bedInfo = new EmptyBedsResponse();
            bedInfo.setAreaCode(info.getNurseCellCode());  //院区编码
            bedInfo.setAreaName(info.getNurseCellName());   //病区名称
            bedInfo.setDeptCode(info.getDeptCode());        //科室编码
            bedInfo.setDeptName(info.getDeptName());       // 科室名称
            bedInfo.setYeadCode(info.getYard());          //院区编码
            if (info.getYard().equals("1"))               //三香浒关的编码  1是三香 2是浒关
            {
                bedInfo.setYeadName("三香总院");
            } else if (info.getYard().equals("2")) {
                bedInfo.setYeadName("浒关院区");
            }
            bedInfo.setBedsCount(size);   // 集管位总数
            bedInfo.setUsedBedsCount(filterSize); //预绑定床位总数
            bedInfo.setLeaveHospitalToday(leaveHospitalToday);//今日出院患者总数
            bedInfo.setLeaveHospitalTomorrow(leaveHospitalTomorrow);//明日出院患者总数
            resultBeds.add(bedInfo);
        }
        //科室名称特殊处理
        resultBeds.forEach(item -> {
            switch (item.getAreaCode()) {

                case "2509":
                    item.setDeptName("肝胆外科");
                    break;
                case "2510":
                    item.setDeptName("胃肠外科");
                    break;
                case "2511":
                    item.setDeptName("关节外科");
                    break;
                case "2609":
                    item.setDeptName("甲乳外科");
                    break;
                case "2611":
                    item.setDeptName("脊柱外科");
                    break;
                case "2731":
                    item.setDeptName("ICU-A");
                    break;
                case "2732":
                    item.setDeptName("ICU-B");
                    break;
                case "2733":
                    item.setDeptName("ICU-C");
                    break;
                case "2734":
                    item.setDeptName("ICU-D");
                    break;
                default:
                    break;
            }
        });
        resultBeds = resultBeds.stream()
                .sorted(Comparator.comparing(EmptyBedsResponse::getAreaCode))
                .collect(Collectors.toList());
        return resultBeds;
    }

    @Override
    public Object getPreBoundBedDetail(AllSickBedsRequest param) {
        List<HisCwglBed> ylzzNameList = new ArrayList<>();
        List<LeaveAdviceVO> leaveAdviceVOList = new ArrayList<>();
        //获取已经预绑定的患者信息
        LambdaQueryWrapper<PatientBedMiddlePrebundled> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PatientBedMiddlePrebundled::getYard, param.getDistrictCode())
                .eq(PatientBedMiddlePrebundled::getNurseCellCode, param.getAreaCode())
                .eq(PatientBedMiddlePrebundled::getDeptCode, param.getDeptCode())
                .eq(PatientBedMiddlePrebundled::getState, "1");
        List<PatientBedMiddlePrebundled> patientBedMiddlePrebundleds = baseMapper.selectList(lambdaQueryWrapper);
        List<String> prebundledsBedNo = patientBedMiddlePrebundleds.stream()
                .map(PatientBedMiddlePrebundled::getBedNo)
                .collect(Collectors.toList());
        //根据院区获取所有预绑定的集管床位
        List<HisCwglBed> boundGyBeds = baseMapper.getBoundGyBeds(param);
        if (org.springframework.util.CollectionUtils.isEmpty(boundGyBeds)) {
            return new ArrayList<>();
        }
        //判断改床位是否被预绑定过，给标签赋值
//        for (String preBedNo : prebundledsBedNo) {
//            for (HisCwglBed boundGyBed : boundGyBeds) {
//                if (boundGyBed.getBedNo().equals(preBedNo)) {
//                    boundGyBed.setPrebundledType("1");
//                } else {
//                    boundGyBed.setPrebundledType("0");
//                }
//            }
//        }
        boundGyBeds.forEach(item -> {
            item.setPrebundledType(prebundledsBedNo.contains(item.getBedNo()) ? "1" : "0");
        });
        SetSexRoom(boundGyBeds);
        //获取占床人员信息 从这里开始改2/22
        for (HisCwglBed bed : boundGyBeds) {
            PatientBedMiddlePrebundled matchOccBed = patientBedMiddlePrebundleds.stream()
                    .filter(t -> t.getBedNo().equals(bed.getBedNo()))
                    .findFirst()
                    .orElse(null);
            if (matchOccBed != null) {
                bed.setPatinetName(matchOccBed.getName());
                bed.setOccupationState("0");
                bed.setOccupationId(matchOccBed.getId());
            }
        }
        //根据住院证ZY***匹配住院视图，取医疗组组长姓名编号
        List<HisCwglBed> zyLike = new ArrayList<>();
        for (HisCwglBed hisCwglBed : boundGyBeds) {
            HisCwglBed copy = new HisCwglBed();
            if (hisCwglBed.getInpatientNo() == null) {
                continue;
            }
            BeanUtils.copyProperties(hisCwglBed, copy);
            zyLike.add(copy);
        }
        if (!zyLike.isEmpty()) {
            List<String> inpatientNoList = zyLike.stream().map(HisCwglBed::getInpatientNo).collect(Collectors.toList());
            //这里加判断是因为，床位系统里的查询不会出现住院证超过1000的情况，只有在外链查询的时候才会超过1000的情况
            if (inpatientNoList.size() > 1000) {
                int batchSize = 1000;
                List<List<String>> batches = Lists.partition(inpatientNoList, batchSize);
                for (List<String> batchList : batches) {
                    List<HisCwglBed> ylzzNameVO = thisIiInmaininfoMapper.listYlzzNameList(batchList);
                    ylzzNameList.addAll(ylzzNameVO);
                    List<LeaveAdviceVO> leaveAdviceVO = thisIiPrepayinMapper.leaveAdviceInpatientNoList(batchList);
                    leaveAdviceVOList.addAll(leaveAdviceVO);
                }
            } else if (inpatientNoList.size() < 1000) {
                ylzzNameList = thisIiInmaininfoMapper.listYlzzNameList(inpatientNoList);
                leaveAdviceVOList = thisIiPrepayinMapper.leaveAdviceInpatientNoList(inpatientNoList);
            }
            for (HisCwglBed item : ylzzNameList) {
                for (HisCwglBed hisCwglBed : boundGyBeds) {
                    if (item.getInpatientNo()
                            .equals(hisCwglBed.getInpatientNo()) && hisCwglBed.getPatinetName() != null) {
                        hisCwglBed.setYlzzCode(item.getYlzzCode());
                        hisCwglBed.setYlzzName(item.getYlzzName());
                    }
                }
            }
            //选择床位”背景色标注“今日出院”，“明日出院”的患者，用不同色醒目区分
            //出院医嘱的患者信息
            for (LeaveAdviceVO leaveAdviceVO : leaveAdviceVOList) {
                for (HisCwglBed info : boundGyBeds) {
                    if (leaveAdviceVO.getInpatientNo().equals(info.getInpatientNo())) {
                        String changeType = leaveAdviceVO.getChangeType();
                        if ("临时出院".equals(changeType) || "自动出院".equals(changeType)) {
                            info.setChangeType("今日出院");
                        } else {
                            info.setChangeType(leaveAdviceVO.getChangeType());
                        }
                    }
                }
            }
        }
        Map<String, List<HisCwglBed>> groupList = boundGyBeds.stream()
                .collect(Collectors.groupingBy(HisCwglBed::getRoomNo));
        List<BedsDetailInfo> resultLst = new ArrayList<>();
        Iterator<String> it = groupList.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            BedsDetailInfo info = new BedsDetailInfo();
            info.setRoomNum(key);
            info.setChildren(groupList.get(key));
            resultLst.add(info);
        }
        //如果房 间 号不全为数字,排序特殊处理
        List<BedsDetailInfo> strList = new ArrayList<>();
        List<BedsDetailInfo> intList = new ArrayList<>();
        Pattern pattern = Pattern.compile("[0-9]*");
        for (BedsDetailInfo item : resultLst) {
            if (pattern.matcher(item.getRoomNum()).matches()) {
                item.setIntRoomNum(Integer.valueOf(item.getRoomNum()));
                intList.add(item);
            } else {
                strList.add(item);
            }
        }
        strList = strList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getRoomNum))
                .collect(Collectors.toList());
        intList = intList.stream()
                .sorted(Comparator.comparing(BedsDetailInfo::getIntRoomNum))
                .collect(Collectors.toList());
        resultLst = new ArrayList<>();
        resultLst.addAll(strList);
        resultLst.addAll(intList);
        return resultLst;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateTrueBinding(String bedNo) {
        PatientBedMiddle patientBedMiddle = new PatientBedMiddle();
        PatientBedMiddlePrebundled copy = baseMapper.getPatientById(bedNo);
        if (copy == null) {
            return new Response(200, "此床位无预绑患者，跳过----");
        }
        BigDecimal preid = copy.getPreid();
        patientBedMiddle.setId(copy.getId());
        if (copy.getInpatientNo() != null) {
            patientBedMiddle.setInpatientNo(copy.getInpatientNo());
        }
        patientBedMiddle.setIdenno(copy.getIdenno());
        patientBedMiddle.setPreid(preid);
        patientBedMiddle.setYard(copy.getYard());
        patientBedMiddle.setNurseCellCode(copy.getNurseCellCode());
        patientBedMiddle.setNurseCellName(copy.getNurseCellName());
        patientBedMiddle.setDeptCode(copy.getDeptCode());
        patientBedMiddle.setDeptName(copy.getDeptName());
        patientBedMiddle.setBedNo(copy.getBedNo());
        patientBedMiddle.setState(copy.getState());
        if (copy.getOperNo() != null) {
            patientBedMiddle.setOperNo(copy.getOperNo());
        }
        if (copy.getOpenName() != null) {
            patientBedMiddle.setOpenName(copy.getOpenName());
        }
        if (copy.getOperTime() != null) {
            patientBedMiddle.setOperTime(copy.getOperTime());
        }
        if (copy.getNurseCellCodeBefore() != null) {
            patientBedMiddle.setNurseCellCodeBefore(copy.getNurseCellCodeBefore());
        }
        //先修改预绑定表状态
        LambdaUpdateWrapper<PatientBedMiddlePrebundled> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(PatientBedMiddlePrebundled::getPreid, preid)
                .eq(PatientBedMiddlePrebundled::getBedNo, bedNo)
                .eq(PatientBedMiddlePrebundled::getState, "1")
                .set(PatientBedMiddlePrebundled::getState, "3")
                .set(PatientBedMiddlePrebundled::getUpdateTime, LocalDateTime.now());
        boolean update = update(lambdaUpdateWrapper);
        //预绑定患者数据插入到Middle表中
        int insert = patientBedMiddleMapper.insert(patientBedMiddle);
        //修改预约登记表为已登记 REGISTE_STATUS
        LambdaUpdateWrapper<ThisIiPrepayin> lambdaUpdateWrapper1 = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper1.eq(ThisIiPrepayin::getPreid, preid).set(ThisIiPrepayin::getRegisteStatus, "1")
                .set(ThisIiPrepayin::getBedNo,bedNo);
        boolean update1 = thisIiPrepayinService.update(lambdaUpdateWrapper1);
        if (!update || insert < 1 || !update1) {
            return new Response(500, "预绑定转为真实绑定失败");
        }

        //绑定成功后发送短信
        new Thread(() -> {
            try {
                //根据病人PreId获取电子一体化床位申请信息
                ApplicationBed applicationBed = applicationBedMapper.selectById(preid);
                //根据病人PreId获取病人信息
                ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(preid);
                //根据床位编码获取床位信息
                HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, copy.getBedNo())).get(0);
                String userName = "预绑定操作";
                String userId = "systemAuto";
                MsgInfo msgInfo = patientBedMiddleService.getMsgInfo(applicationBed, patientInfo, userId, userName, hisCwglBed, "", 1);
                //发送MQ   （这个是发给个人的）
                patientBedMiddleService.setMsg(msgInfo);
                //再发一次  （这个是发给科室|病区的）
                patientBedMiddleService.setDeptMsg(msgInfo);
                //发送企业微信
                if (msgInfo.getWechatAccountCode() != null && !msgInfo.getWechatAccountCode().isEmpty()) {
                    //企业微信返回josn消息体
                    //调用post发送企业微信消息
                    WeChatLog weChatLog = SendCardMsg.send2(msgInfo);
                    weChatLogMapper.insert(weChatLog);
                    //调用医院发送手机短信的接口
                    TelMessageLog telMessageLog = SendCardMsg.sendTelMessage(msgInfo, 0);
                    telMessageMapper.insert(telMessageLog);
                }
            } catch (Exception ex) {
                int a = 0;
            }
        }).start();
        return new Response(200, "预绑定转为真实绑定成功");
    }


    @Override
    public Map<String, Object> getThisIiPrepayinPrebundled(InpatientRegistrationCondition condition) {
        Map<String, Object> resultMap = new HashMap<>(2);
        String stayInBed = condition.getStayInBed();
        if (!"1".equals(stayInBed)) {
            condition.setStayInBed(null);
        }
        //预绑定患者集合
        List<PatientBedMiddlePrebundled> patientBedMiddlePrebundleds = baseMapper.patientList();
        //门诊
        Integer nullPorint = condition.getOutpatientPageNum();
        if (ObjectUtil.isNotNull(nullPorint)) {
            condition.setCode("1");
            // 获取所有 门诊 患者
            List<ThisIiPrepayin> thisIiPrepayins = thisIiPrepayinMapper.getThisIiPrepayins(condition);
            if (!patientBedMiddlePrebundleds.isEmpty()) {
                List<BigDecimal> preidList = patientBedMiddlePrebundleds.stream()
                        .map(PatientBedMiddlePrebundled::getPreid)
                        .collect(Collectors.toList());
                thisIiPrepayins = thisIiPrepayins.stream()
                        .filter(t -> preidList.contains(t.getPreid()))
                        .collect(Collectors.toList());
                for (ThisIiPrepayin item : thisIiPrepayins) {
                    for (PatientBedMiddlePrebundled item2 : patientBedMiddlePrebundleds) {
                        if (item.getPreid().equals(item2.getPreid()) && item2.getState().equals("1")) {
                            item.setBedNo(item2.getBedNo());
                        }
                    }
                }
                resultMap.put("outpatient", thisIiPrepayins);
            } else {
                List<ThisIiPrepayin> nullList = new ArrayList<>();
                resultMap.put("outpatient", nullList);
            }
        }
        //急诊
        Integer nullPointCheck = condition.getEmergencyCallPageNum();
        if (ObjectUtil.isNotNull(nullPointCheck)) {
            condition.setCode("2");
//            PageHelper.startPage(nullPointCheck, 15, false);
            List<ThisIiPrepayin> thisIiPrepayins = thisIiPrepayinMapper.getThisIiPrepayins(condition);
            if (!patientBedMiddlePrebundleds.isEmpty()) {
                List<BigDecimal> preidList = patientBedMiddlePrebundleds.stream()
                        .map(PatientBedMiddlePrebundled::getPreid)
                        .collect(Collectors.toList());
                thisIiPrepayins = thisIiPrepayins.stream()
                        .filter(t -> preidList.contains(t.getPreid()))
                        .collect(Collectors.toList());
                thisIiPrepayins = thisIiPrepayins.stream()
                        .sorted(Comparator.comparing(ThisIiPrepayin::getPredate).reversed())
                        .collect(Collectors.toList());
                for (ThisIiPrepayin item : thisIiPrepayins) {
                    for (PatientBedMiddlePrebundled item2 : patientBedMiddlePrebundleds) {
                        if (item.getPreid().equals(item2.getPreid()) && item.getStatus().equals("1")) {
                            item.setBedNo(item2.getBedNo());
                        }
                    }
                }
                resultMap.put("emergencyCall", thisIiPrepayins);
            } else {
                List<ThisIiPrepayin> nullList = new ArrayList<>();
                resultMap.put("emergencyCall", nullList);
            }
        }
        return resultMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response unbind(String bedId, String name) {
        LambdaUpdateWrapper<PatientBedMiddlePrebundled> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(PatientBedMiddlePrebundled::getName, name)
                .eq(PatientBedMiddlePrebundled::getBedNo, bedId)
                .eq(PatientBedMiddlePrebundled::getState, "1")
                .set(PatientBedMiddlePrebundled::getState, "3");
        boolean update = update(lambdaUpdateWrapper);
        if (!update) {
            return new Response(500, "预绑定取消失败");
        }
        return new Response(200, "预绑定取消成功");
    }


    /**
     * 给病床赋属性
     *
     * @param boundGyBeds 所有病床信息
     * @return 1.将非空床的人员先进行性别赋值(根据别人住院信息)
     * 2.根据病区-科室-房间号进行分组
     * 3.判断每组的床位数，小于等于3的为高级病房，否则为普通病房
     * 4.高级病房判断有没有住人，如果有人住院，其他床位的属性赋成该病人属性
     * cww
     */
    private List<HisCwglBed> SetSexRoom(List<HisCwglBed> boundGyBeds) {
        //呼吸科不分高级病房，空床全部默认为不分性别
        List<String> specialDept = new ArrayList<>();
        specialDept.add("2615-1023");  //西十五病区   呼吸科
        //获取所有在床人员信息
        List<spdVO> allInBedList = thisIiInmaininfoMapper.getInBedInfo(new ArrayList<>());
        //获得床位号
        List<String> inBedNoList = allInBedList.stream().map(spdVO::getBedNo).collect(Collectors.toList());
        //获得病床号编码
        List<String> allBedNos = boundGyBeds.stream().map(t -> t.getBedNo()).collect(Collectors.toList());
        List<spdVO> inBedList = allInBedList.stream()
                .filter(t -> allBedNos.contains(t.getBedNo()))
                .collect(Collectors.toList());
        CommonMethod methodClass = new CommonMethod();
        //初始化
        boundGyBeds.forEach(item -> {
            item.setSex("3");
            item.setBedSex("3");
            item.setSexColor(com.cw.constant.Constants.threeDiv);
            item.setName(methodClass.getBedName(item.getBedNo()));
        });

        List<HisCwglBed> highGradeBedLst = new ArrayList<>(); //高级病房床位
        List<HisCwglBed> generalBedLst = new ArrayList<>();//普通病房床位
        Map<String, List<HisCwglBed>> groupBeds = boundGyBeds.stream()
                .collect(Collectors.groupingBy(t -> t.getNurseCellCode() + "-" + t.getDeptCode() + "-" + t.getRoomNo()));
        Iterator<String> it = groupBeds.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            List<HisCwglBed> keyList = groupBeds.get(key);
            if (keyList.size() <= seniorRoomNum) {
                highGradeBedLst.addAll(keyList);
            } else {
                generalBedLst.addAll(keyList);
            }
        }

        /**
         * 高级病房床位性别处理
         * */
        //高级病房非空床
        List<HisCwglBed> highGradeNoEmptyBedList = highGradeBedLst.stream()
                .filter(t -> inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());
        //高级病房非空床赋值
        highGradeNoEmptyBedList.forEach(item -> {
            spdVO matchInfo = inBedList.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            SetSexValue(matchInfo, item);
            item.setBedState("a");//将床位状态赋为a,因为数据库的床位状态数据不一定准确

        });
        //普通病房床位性别处理
        //普通病房非空床
        List<HisCwglBed> generalNoEmptyBedList = generalBedLst.stream()
                .filter(t -> inBedNoList.contains(t.getBedNo()))
                .collect(Collectors.toList());
        //普通病房非空床赋值
        generalNoEmptyBedList.forEach(item -> {
            spdVO matchInfo = inBedList.stream()
                    .filter(t -> t.getBedNo().equals(item.getBedNo()))
                    .findFirst()
                    .orElse(null);
            SetSexValue(matchInfo, item);
            item.setBedState("a");//将床位状态赋为a,因为数据库的床位状态数据不一定准确
        });
        return boundGyBeds;
    }

    /**
     * 给床位赋性别属性
     */
    private void SetSexValue(spdVO matchInfo, HisCwglBed item) {
        if ((matchInfo != null && matchInfo.getSex() != null)) {
            item.setSex(matchInfo.getSex());
            item.setBedSex(matchInfo.getSex());
            if (matchInfo.getSex().equals("1")) {
                item.setSexColor(com.cw.constant.Constants.oneDiv);
            } else if (matchInfo.getSex().equals("2")) {
                item.setSexColor(com.cw.constant.Constants.fourDiv);
            }
        }
    }
}
